package xiong.myiot;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;
import org.litepal.crud.DataSupport;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity implements MQTTGetMessageCallBack {
    private int add_site_step;
    // click id
    private String click_uuid = "";
    private int click_position;
    private String Telephone = "";
    private String Password = "";
    // 登录活动获取返回内容 id
    private static final int ACTIVITY_REQUEST_CODE_LOGIN = 1;
    private String TAG = "MAIN";
    private String captureResult;
    private String telephone = "17740171896";
    //    mqtt服务
    private MQTTServiceConnection serviceConnection;
    private MQTTService mqttService;
    //    瀑布流控件
    private List<Site> siteList = new ArrayList<>();
    private SiteAdapter siteAdapter;

    private TextView mTextMessage;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    mTextMessage.setText(R.string.title_home);
                    querySite_db();
                    return true;
                case R.id.navigation_dashboard:
                    mTextMessage.setText(R.string.title_dashboard);
//                    MQTTService.publish("ff6be6ebb6","XY+ST="+telephone);
                    captureResult = "ff6be6ebb6";
                    MQTTService.publish(captureResult, "XY+ST=" + telephone);
                    return true;
                case R.id.navigation_notifications:
                    mTextMessage.setText(R.string.title_notifications);

//                    addSite_db();
                    Toast.makeText(MainActivity.this, "添加数据库成功", Toast.LENGTH_SHORT).show();
                    return true;
            }
            return false;
        }
    };

    /**
     * 创建菜单
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /**
     * 菜单点击时间对应到相应函数中
     *
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            // 注册按钮，打开注册页面
            case R.id.login_item:
                LoginItem("请登陆");
                break;
            case R.id.scan_item:
                CaptureScanItem("请扫描二维码");
                break;
            default:
                break;
        }
        return true;
    }

    /**
     * 菜单登录功能
     *
     * @param info 登陆提示信息
     */
    public void LoginItem(String info) {
//        is_login_succes = false;
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        intent.putExtra("tip", info);  // 传递参数，根据需要填写
        startActivityForResult(intent, ACTIVITY_REQUEST_CODE_LOGIN);
    }

    /**
     * 菜单二维码扫描功能
     *
     * @param tip 二维码扫描提示
     */
    public void CaptureScanItem(String tip) {
        new IntentIntegrator(this)
                .setCaptureActivity(CustomCaptureActivity.class)
                .setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)// 扫码的类型,可选：一维码，二维码，一/二维码
                .setPrompt(tip)// 设置提示语
                .setCameraId(0)// 选择摄像头,可使用前置或者后置
                .setBeepEnabled(true)// 是否开启声音,扫完码之后会"哔"的一声
                .setBarcodeImageEnabled(true)// 扫完码之后生成二维码的图片
                .initiateScan();// 初始化扫码
    }

    /**
     * 子Activity 返回结果到主Activity中
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case ACTIVITY_REQUEST_CODE_LOGIN:
                if (resultCode == 2) {
                    Telephone = data.getStringExtra("telephone");
                    Password = data.getStringExtra("password");
                    //通过日志和控制台将返回的数据打印出来
                    Log.d(TAG, Telephone);
                    Log.d(TAG, Password);
                }
                break;
            default:
                break;
        }
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
                //绑定设备
                captureResult = result.getContents();
                MQTTService.publish(captureResult, "XY+ST=" + telephone);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //数据库连接创建
        LitePal.getDatabase();
        //mqtt连接
        serviceConnection = new MQTTServiceConnection();
        serviceConnection.setIGetMessageCallBack(MainActivity.this);
        Intent intent = new Intent(this, MQTTService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);

        mTextMessage = (TextView) findViewById(R.id.message);
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        // 瀑布流显示
        initRecyclerView();
        // 数据库查询
        querySite_db();

        addSite_db("测试站点1","ff6be6ebb6","XYS01-GPRS");
        addSite_db("测试阀门1","fe6be6ebb6","XYN01-TAP");
    }

    /**
     * 设备RecyclerView初始化
     */
    public void initRecyclerView(){
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
//        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        GridLayoutManager layoutManager = new GridLayoutManager(this,3);
        recyclerView.setLayoutManager(layoutManager);
        siteAdapter = new SiteAdapter(siteList);
        recyclerView.setAdapter(siteAdapter);

        RecyItemTouchHelperCallback itemTouchHelperCallback = new RecyItemTouchHelperCallback(siteAdapter, false, true);
        final ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemTouchHelperCallback);
        itemTouchHelper.attachToRecyclerView(recyclerView);

        recyclerView.addOnItemTouchListener(new OnRecyclerItemClickListener(recyclerView) {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder) {
            }
            @Override
            public void onLongClick(RecyclerView.ViewHolder viewHolder) {
                Toast.makeText(MainActivity.this, "" + "长按拖动...", Toast.LENGTH_SHORT).show();
                itemTouchHelper.startDrag(viewHolder);
            }
        });
        // 点击显示设备详细信息，回调
        siteAdapter.ViewItemOnClick(new SiteAdapter.ViewItemInterface() {
            @Override
            public void onclick(View view, int position) {
                Site site = siteList.get(position); // 根据位置获取点击的item
                click_uuid = site.uuid;
                click_position = position;
                Log.d(TAG,click_uuid);
//                Intent intent = new Intent(MainActivity.this, TapSettingActivity.class);
//                intent.putExtra("tip", "测试");  // 传递参数，根据需要填写
//                startActivityForResult(intent, ACTIVITY_REQUEST_CODE_LOGIN);
            }
        });
        // 图片按钮响应事件，回调
        siteAdapter.ImageBtnOnClick(new SiteAdapter.ImageBtnInterface() {
            @Override
            public void onclick(View view, int position) {
                Site site = siteList.get(position); // 根据位置获取点击的item
                click_uuid = site.uuid;
                click_position = position;
                if (site.imageStatusId == R.drawable.switch_open3) {
                    // 关闭水管
                    MQTTService.publish(site.uuid, "XY+TAP=0");
                } else {
                    // 打开水管
                    MQTTService.publish(site.uuid, "XY+TAP=1");
                }
            }
        });
    }

    /**
     * 更新设备控件显示
     * @param uuid
     * @param info
     */
    public void updateSiteItem(String uuid, String info) {
        Log.d(TAG,uuid + ":" + info);
        for(int i=0 ; i<siteList.size();i++){
            Site site = siteList.get(i);
            if(site.uuid.equals(uuid)){
                Log.d(TAG,uuid + ":" + site.name);
                if(info.equals("online")){
                    site.status="设备在线";
                    siteAdapter.notifyItemChanged(i);
                }
                break;
            }
        }
    }

    /**
     * mqtt 服务接收订阅消息
     *
     * @param message
     */
    @Override
    public void setMessage(String topic, String message) {
        Log.d(TAG,"MQTT Recv [" + topic + "]:" + message);
        Matcher matcher_info = Pattern.compile("^([a-zA-Z0-9]{10}):(.*?)$").matcher(message);
        if(matcher_info.find()){
            String uuid = matcher_info.group(1);
            String info = matcher_info.group(2);
            updateSiteItem(uuid,info);
        }
//        boolean matches = Pattern.matches("^([a-zA-Z0-9]{10}):(.*?)$", content);
//        if (topic.equals(telephone)) {
            if (message.startsWith("INF:")) {
                String inf = message.substring("INF:".length(), message.length());
                try {
                    Log.d(TAG,"测试");
                    final JSONObject data = new JSONObject(inf);
                    addSite_db(
                            data.getString("name"),
                            data.getString("uuid"),
                            data.getString("version")
                    );
                } catch (JSONException e) {
                    Log.d(TAG, e.toString());
                }
            }
            if (message.equals("TAP:1")) {
                Log.d(TAG, click_uuid+"   index:"+click_position);
                Site site = siteList.get(click_position);
                site.imageStatusId = R.drawable.switch_open3;
                siteAdapter.notifyItemChanged(click_position);
            }
            if (message.equals("TAP:0")) {
                Log.d(TAG, click_uuid);
                Site site = siteList.get(click_position);
                site.imageStatusId = R.drawable.switch_close3;
                siteAdapter.notifyItemChanged(click_position);
            }
//        }
        mqttService = serviceConnection.getMqttService();
        mqttService.toCreateNotification(message);
    }

    /**
     * 添加一条设备信息到siteList中
     */
    public void addSiteItemOne(String name, String uuid, String position, int alive, String status) {
        int imageBtnId;
        if (uuid.startsWith("ff")) {
            imageBtnId = R.drawable.site;
        } else {
            imageBtnId = R.drawable.pipe;
        }
        int imageStatusId;
        if (status.equals("打开")) {
            imageStatusId = R.drawable.switch_open3;
        } else {
            imageStatusId = R.drawable.switch_close3;
        }
        Site site_item = new Site(
                name,
                uuid,
                position,
                status,
                imageBtnId,
                imageStatusId);
        siteList.add(site_item);
    }

    /**
     * 数据库添加一条Site信息
     */
    public void addSite_db(String name, String uuid, String version) {
        List<TBsite> sites = DataSupport.where("uuid = ?", uuid).find(TBsite.class);
        if (sites.size() > 0) {
            Toast.makeText(MainActivity.this, "设备已存在", Toast.LENGTH_LONG).show();
        } else {
            TBsite tBsite = new TBsite();
            tBsite.setName(name);
            tBsite.setUuid(uuid);
            tBsite.setPosition("位置");
            tBsite.setAlive(1);
            tBsite.setStatus("在线");
            tBsite.setAddDate(new Date(System.currentTimeMillis()));
            tBsite.save();
            if (uuid.startsWith("ff")) {
                Log.d(TAG, "获取设备为-->终端");
            }
            if (uuid.startsWith("fe")) {
                Log.d(TAG, "获取设备为-->节点");
            }
            querySite_db();
        }
    }

    /**
     * 刷新查询显示所有设备
     */
    public void querySite_db() {
        siteList.clear();
        List<TBsite> tBsites = DataSupport.findAll(TBsite.class);
        for (TBsite tBsite : tBsites) {
            Log.d(TAG, tBsite.getId() + "  name:" + tBsite.getName() + "alive:" + tBsite.getAlive());
            addSiteItemOne(tBsite.getName(), tBsite.getUuid(), tBsite.getPosition(), tBsite.getAlive(), tBsite.getStatus());
        }
    }

    /**
     * 数据库添加一条Node信息
     */
    public void addNode_db() {

    }

    @Override
    protected void onDestroy() {
        unbindService(serviceConnection);
        super.onDestroy();
    }

}
